package com.xms.queryview.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xms.core.model.PagedList;
import com.xms.queryview.api.model.QueryViewAllInfoModel;
import com.xms.queryview.api.model.QueryViewLayoutConfigModel;
import com.xms.queryview.entity.QueryView;
import com.xms.queryview.service.IQueryViewFinderService;
import com.xms.ribbonbutton.entity.RibbonButton;
import com.xms.ribbonbutton.service.IRibbonButtonFinderService;
import com.xms.schema.entity.Attribute;
import com.xms.sdk.core.query.QueryExpression;
import com.xms.sdk.extensions.IQueryMetadataFinder;
import com.xms.security.service.principal.ISystemUserPermissionService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.JsonUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import com.xms.webresource.entity.WebResource;
import com.xms.webresource.service.IWebResourceContentCoder;
import com.xms.webresource.service.IWebResourceFinderService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author migo
 * @since 2021-08-29
 */
@RestController
@RequestMapping("{org}/api/schema/queryview")
public class QueryViewFinderController extends ApiBaseController {
    private IQueryViewFinderService _queryViewFinderService;
    private IQueryMetadataFinder _queryMetadataFinder;
    private IRibbonButtonFinderService _ribbonButtonFinderService;
    private IWebResourceFinderService _webResourceFinderService;
    private IWebResourceContentCoder _webResourceContentCoder;
    private ISystemUserPermissionService _systemUserPermissionService;

    @Autowired
    public QueryViewFinderController(IQueryViewFinderService queryViewFinderService
            , IQueryMetadataFinder queryMetadataFinder
            , IRibbonButtonFinderService ribbonButtonFinderService
            , IWebResourceFinderService webResourceFinderService
            , IWebResourceContentCoder webResourceContentCoder
            , ISystemUserPermissionService systemUserPermissionService) {
        _queryViewFinderService = queryViewFinderService;
        _queryMetadataFinder = queryMetadataFinder;
        _ribbonButtonFinderService = ribbonButtonFinderService;
        _webResourceFinderService = webResourceFinderService;
        _webResourceContentCoder = webResourceContentCoder;
        _systemUserPermissionService = systemUserPermissionService;
    }

    @ApiOperation("查询视图列表")
    @GetMapping("list")
    public JsonResultObject get(@RequestParam(value = "entityid", required = true) UUID entityId,
                                @RequestParam(name = "name", required = false) String name,
                                @RequestParam(name = "getall", required = false) Boolean getall,
                                @RequestParam(name = "page", required = false) Integer page,
                                @RequestParam(name = "pagesize", required = false) Integer pagesize,
                                @RequestParam(value = "sortby", required = false) String sortby,
                                @RequestParam(value = "sortdirection", required = false) String sortdirection) {
        if (UUIDUtil.isEmpty(entityId)) {
            return JNotSpecifiedParams("entityid");
        }
        LambdaQueryWrapper<QueryView> lambdaQueryWrapper = getSortedQueryWrapper(sortby, sortdirection);
        lambdaQueryWrapper.eq(QueryView::getEntityid, entityId);
        if (StringUtil.notEmpty(name)) {
            lambdaQueryWrapper.like(QueryView::getName, name);
        }
        if (getall != null && getall) {
            return JOk(_queryViewFinderService.list(lambdaQueryWrapper));
        } else if (page == null || pagesize == null) {
            return JNotSpecifiedParams("page", "pagesize");
        }
        page = (page <= 0 ? 1 : page);
        pagesize = (pagesize <= 0 ? 10 : pagesize);
        IPage<QueryView> datas = _queryViewFinderService.page(new Page<>(page, pagesize), lambdaQueryWrapper);
        PagedList<QueryView> result = new PagedList<>(datas.getRecords(), page, pagesize, datas.getTotal(), datas.getPages());

        return JOk(result);
    }

    @ApiOperation("查询视图")
    @GetMapping("getbyid/{id}")
    public JsonResultObject getById(@PathVariable(value = "id", required = true) UUID id) {
        QueryView queryView = _queryViewFinderService.getById(id);
        if (queryView == null) {
            return JNotFound();
        }
        return JOk(queryView);
    }

    @ApiOperation("查询视图")
    @GetMapping("getbyentityid")
    public JsonResultObject getByEntityId(@RequestParam(value = "entityid", required = true) UUID entityId,
                                          @RequestParam(value = "authorized", required = false) Boolean authorized) {
        List<QueryView> result = null;
        if (authorized != null && authorized) {
            result = _queryViewFinderService.getAuthorizedByEntityId(entityId);
        } else {
            result = _queryViewFinderService.getByEntityId(entityId);
        }
        return JOk(result);
    }

    @ApiOperation("查询视图")
    @GetMapping("getbyentityname")
    public JsonResultObject getByEntityName(@RequestParam(value = "entityname", required = true) String entityName,
                                            @RequestParam(value = "authorized", required = false) Boolean authorized) {
        List<QueryView> result = null;
        if (authorized != null && authorized) {
            result = _queryViewFinderService.getAuthorizedByEntityName(entityName);
        } else {
            result = _queryViewFinderService.getByEntityName(entityName);
        }
        return JOk(result);
    }

    @ApiOperation("查询视图字段")
    @GetMapping("getattributes/{id}")
    public JsonResultObject getAttributes(@PathVariable(value = "id", required = true) UUID id) {
        QueryView queryView = _queryViewFinderService.getById(id);
        if (queryView == null) {
            return JNotFound();
        }
        QueryExpression queryExp = JsonUtil.toBean(queryView.getFetchconfig(), QueryExpression.class);
        List<Attribute> result = _queryMetadataFinder.getAttributes(queryExp);
        return JOk(result);
    }

    @ApiOperation("查询视图按钮")
    @GetMapping("getbuttons/{id}")
    public JsonResultObject getButtons(@PathVariable(value = "id", required = true) UUID id) {
        QueryView queryView = _queryViewFinderService.getById(id);
        if (queryView == null) {
            return JNotFound();
        }
        List<RibbonButton> buttons = _ribbonButtonFinderService.getByEntityId(queryView.getEntityid());
        if (queryView.getIscustombutton() && StringUtil.notEmpty(queryView.getCustombuttons())) {
            List<UUID> buttonid = JsonUtil.toList(queryView.getCustombuttons(), UUID.class);
            buttons.removeIf(x -> !buttonid.contains(x.getRibbonbuttonid()));
        }
        return JOk(buttons);
    }

    @ApiOperation("查询视图信息")
    @GetMapping("getviewinfo")
    public JsonResultObject getViewInfo(@RequestParam(value = "id", required = false) UUID id,
                                        @RequestParam(value = "entityid", required = false) UUID entityId,
                                        @RequestParam(value = "entityname", required = false) String entityName) throws UnsupportedEncodingException {
        //视图信息
        List<QueryView> views = null;
        //字段信息
        List<Attribute> attributes = null;
        //按钮信息
        List<RibbonButton> buttons = null;
        //Web资源信息
        String webResources = null;
        List<UUID> webResourceIds = null;
        QueryView queryView = null;

        //查询视图信息
        if (UUIDUtil.notEmpty(id)) {
            queryView = _queryViewFinderService.getById(id);
            if (queryView != null) {
                views = new ArrayList<>();
                views.add(queryView);
            }
        } else if (UUIDUtil.notEmpty(entityId)) {
            views = _queryViewFinderService.getAuthorizedByEntityId(entityId);
            if (CollectionUtil.notEmpty(views)) {
                queryView = views.stream().filter(x -> x.getIsdefault()).findFirst().get();
            }
        } else if (StringUtil.notEmpty(entityName)) {
            entityName = entityName.toLowerCase();
            views = _queryViewFinderService.getAuthorizedByEntityName(entityName);
            if (CollectionUtil.notEmpty(views)) {
                queryView = views.stream().filter(x -> x.getIsdefault()).findFirst().get();
            }
        }
        if (queryView == null) {
            return JNotFound();
        }
        //查询字段
        QueryExpression queryExp = JsonUtil.toBean(queryView.getFetchconfig(), QueryExpression.class);
        attributes = _queryMetadataFinder.getAttributes(queryExp);
        //查询按钮
        buttons = _ribbonButtonFinderService.getByListAreaEnabled(queryView.getEntityid());
        if (queryView.getIscustombutton()) {
            if(StringUtil.notEmpty(queryView.getCustombuttons())) {
                List<UUID> buttonid = JsonUtil.toList(queryView.getCustombuttons(), UUID.class);
                if (CollectionUtil.notEmpty(buttonid)) {
                    buttons.removeIf(x -> !buttonid.contains(x.getRibbonbuttonid()));
                }
            }
            else{
                buttons.clear();
            }
        }
        //查询Web资源信息
        if (StringUtil.notEmpty(queryView.getLayoutconfig())) {
            QueryViewLayoutConfigModel layoutConfig = JsonUtil.toBean(queryView.getLayoutconfig(), QueryViewLayoutConfigModel.class);
            if (layoutConfig != null && CollectionUtil.notEmpty(layoutConfig.ClientResources)) {
                webResourceIds = layoutConfig.ClientResources;
            }
        }
        if (CollectionUtil.notEmpty(buttons)) {
            if (webResourceIds == null)
                webResourceIds = new ArrayList<>();
            for (RibbonButton button : buttons) {
                if (StringUtil.notEmpty(button.getJslibrary())) {
                    String[] arr = StringUtil.splitSafe(button.getJslibrary(), ":");
                    if (arr.length > 1) {
                        UUID webResourceId = UUIDUtil.get(arr[1]);
                        webResourceIds.add(webResourceId);
                    }
                }
            }
        }
        if (CollectionUtil.notEmpty(webResourceIds)) {
            StringBuilder content = new StringBuilder();
            List<WebResource> result = _webResourceFinderService.getByIds(webResourceIds);
            for (WebResource item : result) {
                content.append(_webResourceContentCoder.decode(item.getContent()));
            }
            webResources = content.toString();
        } else {
            webResources = "";
        }
        List<UUID> noneReadFields = new ArrayList<>();
        //获取字段权限
        if (!_currentUser.isAdministrator() && attributes.stream().anyMatch(x->x.getAuthorizationenabled()))
        {
            List<UUID> securityFields = attributes.stream().filter(n -> n.getAuthorizationenabled()).map(Attribute::getAttributeid).collect(Collectors.toList());
            if (CollectionUtil.notEmpty(securityFields))
            {
                //无权限的字段
                noneReadFields = _systemUserPermissionService.getNoneReadFields(_currentUser.getUser().SystemUserId, securityFields);
            }
        }
        QueryViewAllInfoModel result = new QueryViewAllInfoModel();
        result.views = views;
        result.attributes = attributes;
        result.buttons = buttons;
        result.webresources = webResources;
        result.nonereadfields = noneReadFields;
        return JOk(result);
    }
}
